package ru.technogeek.labs.android.lego;

import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Controller extends Activity {
    private static final int REQUEST_ENABLE_BT = 0;

    BluetoothAdapter mBluetoothAdapter;
    ArrayAdapter<String> mArrayAdapter;
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // TODO: move BT initialization to separate thread
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // TODO: error
        	// Device does not support Bluetooth
        	return;
        }
        
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
           
        Button conBtn = (Button)findViewById(R.id.ConnectButton);
        conBtn.setOnClickListener(mConnectionBtnListener);        	
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	switch(requestCode) {
    	case REQUEST_ENABLE_BT:
    		if(resultCode == RESULT_OK) {
    			
    		} else if(resultCode == RESULT_CANCELED) {
    			// TODO: Error message
    			return;
    		}
    	}   	
    }
   
    private OnClickListener mConnectionBtnListener = new OnClickListener() {
		public void onClick(View v) {
			browseForAvaliableDevices();
			
		}
    };
    
    private void browseForAvaliableDevices(){
        ListView view = (ListView)findViewById(R.id.ListView01);
        mArrayAdapter = new ArrayAdapter<String>(this, R.layout.item);

    	Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    	// If there are paired devices
    	if (pairedDevices.size() > 0) {
    	    // Loop through paired devices
    	    for (BluetoothDevice device : pairedDevices) {
    	        // Add the name and address to an array adapter to show in a ListView
    	        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    	    }
    	}
    	view.setAdapter(mArrayAdapter);
    	return;
    }
} 